package com.yeraphael.controller;


import com.yeraphael.entity.Clazz;
import com.yeraphael.entity.ClazzQueryParam;
import com.yeraphael.entity.PageBeandf;
import com.yeraphael.entity.Result;
import com.yeraphael.exception.BussinessException;
import com.yeraphael.service.ClazzService;
import com.yeraphael.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/clazzs")
public class ClazzController {

    @Autowired
    private ClazzService clazzService;

    @Autowired
    private StudentService studentService;

    @GetMapping
    public Result getAll(ClazzQueryParam param) {
        log.info("param = {}", param);
        PageBeandf pageBean = clazzService.getAll(param);
        return Result.success(pageBean);
    }

    @PostMapping
    public Result add(@RequestBody Clazz clazz) {
        log.info("clazz = {}", clazz);
        clazzService.addClazz(clazz);
        return Result.success();
    }

    @GetMapping("{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("id = {}", id);
        Clazz Clazz = clazzService.getById(id);
        return Result.success(Clazz);
    }


    @PutMapping
    public Result update(@RequestBody Clazz clazz) {
        log.info("clazz = {}", clazz);
        clazzService.updateClazz(clazz);
        return Result.success();
    }

    @DeleteMapping("{id}")
    public Result delete(@PathVariable Integer id) throws BussinessException {
        Boolean flag = studentService.getStudentCountByClazzId(id);
        if (flag) {
            throw new BussinessException("对不起, 该班级下有学生, 不能直接删除");
        }
        clazzService.deleteClazz(id);
        return Result.success();
    }

    @GetMapping("/list")
    public Result getAllList() {
        List<Clazz> clazzList = clazzService.getAllList();
        return Result.success(clazzList);
    }



}
